package top.javahai.chatroom.service.impl;

import org.springframework.stereotype.Service;
import top.javahai.chatroom.entity.ImgFormat;
import top.javahai.chatroom.service.ScreenShotService;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ScreenShotServiceImpl implements ScreenShotService {

    private Dimension d = Toolkit.getDefaultToolkit().getScreenSize();

    @Override
    public List<Object> snapShot(ImgFormat imgFormat) {
        List<Object> list=new ArrayList<>();
        try {
//拷贝屏幕到一个BufferedImage对象screenshot
//  将一幅图片加载到内存中（BufferedImage生成的图片在内存里有一个图像缓冲区，
//  利用这个缓冲区我们可以很方便地操作这个图片
            BufferedImage screenshot = (new Robot()).createScreenCapture(new
                    Rectangle(0, 0, (int)d.getWidth(), (int) d.getHeight()));
//            截取时间
            Date date = new Date();
            SimpleDateFormat sdformat = new SimpleDateFormat("yyyyMMddHHmmss");// 24小时制
            String LgTime = sdformat.format(date);
//根据文件前缀变量和文件格式变量，自动生成文件名
           imgFormat.setLgTime(LgTime);
            imgFormat.setSaveAddress(imgFormat.getFileName() + LgTime + "." + imgFormat.getImageFormat());
            File f = new File(imgFormat.getSaveAddress());
            System.out.println("-------截图保存地址 " + imgFormat.getSaveAddress()+"--------------");
//将screenshot对象写入图像文件,并返回是否成功
            boolean IsSaveSuccessful=ImageIO.write(screenshot, imgFormat.getImageFormat(), f);
            System.out.println("-------------------------截图成功-----------------------\n");
            list.add(imgFormat);
//            截图成功
            if(IsSaveSuccessful){
                imgFormat.setMsg("截图成功!");
            }else {
                imgFormat.setMsg("截图失败!");
            }
            return list;
        } catch (Exception ex) {
// TODO Auto-generated catch block
            System.out.println(ex);
            return list;
        }
    }

}
